<template>
  <div class="upload-container">
    <div class="header">
      <h2>文件上传</h2>
      <el-button @click="$router.push('/')" plain>返回首页</el-button>
    </div>
    
    <div class="upload-wrapper">
      <el-card shadow="hover">
        <template #header>
          <div class="card-header">
            <span>选择文件上传</span>
            <span class="size-tip">最大支持 500MB</span>
          </div>
        </template>
        
        <div class="upload-form">
          <el-tabs v-model="activeTab" class="custom-tabs">
            <el-tab-pane label="单文件上传" name="single">
              <el-upload
                class="upload-area"
                drag
                :auto-upload="false"
                :limit="1"
                :on-change="handleSingleFileChange"
                :on-exceed="handleExceed"
                :on-remove="handleSingleFileRemove"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                  拖拽文件到此处或 <em>点击上传</em>
                </div>
              </el-upload>
              
              <div class="file-info" v-if="singleFileInfo.file">
                <div class="file-info-header">
                  <el-icon><Document /></el-icon>
                  <span class="file-name">{{ singleFileInfo.file.name }}</span>
                </div>
                <p><strong>文件大小：</strong>{{ formatFileSize(singleFileInfo.file.size) }}</p>
                <p><strong>文件类型：</strong>{{ singleFileInfo.file.type || '未知' }}</p>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="多文件/文件夹上传" name="multiple">
              <div class="multiple-upload-area">
                <div class="upload-buttons">
                  <el-button type="primary" @click="triggerMultipleFileInput">
                    <el-icon><document-add /></el-icon> 选择多个文件
                  </el-button>
                  <el-button type="success" @click="triggerFolderInput">
                    <el-icon><folder-add /></el-icon> 选择文件夹
                  </el-button>
                  <input 
                    type="file" 
                    ref="multipleFileInput" 
                    multiple 
                    style="display: none;" 
                    @change="handleMultipleFileChange"
                  />
                  <input 
                    type="file" 
                    ref="folderInput" 
                    webkitdirectory 
                    style="display: none;" 
                    @change="handleMultipleFileChange"
                  />
                </div>
                
                <div class="selected-files" v-if="multipleFileInfo.files.length > 0">
                  <div class="selected-files-header">
                    <h4>已选择 {{ multipleFileInfo.files.length }} 个文件</h4>
                    <el-button type="danger" link @click="clearMultipleFiles">
                      清空
                    </el-button>
                  </div>
                  
                  <div class="zip-name-input">
                    <el-form-item label="压缩包名称">
                      <el-input v-model="multipleFileInfo.zipName" placeholder="请输入压缩包名称(可选)"/>
                    </el-form-item>
                  </div>
                  
                  <el-table :data="multipleFileInfo.files" style="width: 100%" max-height="250">
                    <el-table-column prop="name" label="文件名" min-width="180" show-overflow-tooltip />
                    <el-table-column label="大小" width="100">
                      <template #default="scope">
                        {{ formatFileSize(scope.row.size) }}
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80">
                      <template #default="scope">
                        <el-button type="danger" link @click="removeMultipleFile(scope.$index)">
                          删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                
                <div v-else class="drop-zone" @dragover.prevent @drop.prevent="onDropFiles">
                  <el-icon style="font-size: 48px;"><upload /></el-icon>
                  <p>拖拽文件或文件夹到此处</p>
                  <p class="drop-hint">也可以使用上方按钮选择文件</p>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
          
          <div class="form-options">
            <el-form label-width="100px">
              <el-form-item label="过期时间">
                <el-select 
                  v-if="activeTab === 'single'"
                  v-model="singleFileInfo.expirationDays" 
                  placeholder="请选择"
                >
                  <el-option label="1天" :value="1" />
                  <el-option label="3天" :value="3" />
                  <el-option label="7天" :value="7" />
                  <el-option label="14天" :value="14" />
                  <el-option label="30天" :value="30" />
                </el-select>
                <el-select 
                  v-else
                  v-model="multipleFileInfo.expirationDays" 
                  placeholder="请选择"
                >
                  <el-option label="1天" :value="1" />
                  <el-option label="3天" :value="3" />
                  <el-option label="7天" :value="7" />
                  <el-option label="14天" :value="14" />
                  <el-option label="30天" :value="30" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="文件描述">
                <el-input
                  v-if="activeTab === 'single'"
                  v-model="singleFileInfo.description"
                  type="textarea"
                  placeholder="请输入文件描述信息（选填）"
                  maxlength="200"
                  show-word-limit
                  :rows="3"
                />
                <el-input
                  v-else
                  v-model="multipleFileInfo.description"
                  type="textarea"
                  placeholder="请输入文件描述信息（选填）"
                  maxlength="200"
                  show-word-limit
                  :rows="3"
                />
              </el-form-item>
            </el-form>
          </div>
          
          <div class="form-actions">
            <el-button
              type="primary"
              :disabled="!isUploadable"
              :loading="uploading"
              @click="handleUpload"
            >
              开始上传
            </el-button>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 上传结果对话框 -->
    <el-dialog
      v-model="uploadResult.visible"
      title="上传成功"
      :width="isMobile ? '95%' : '500px'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      class="upload-result-dialog"
    >
      <div class="result-box">
        <el-result
          icon="success"
          title="文件上传成功"
          sub-title="请妥善保存下面的文件信息，过期后文件将自动删除！"
        >
        </el-result>
        
        <div class="result-info">
          <el-descriptions border direction="vertical" :column="1" class="custom-descriptions">
            <el-descriptions-item label="文件名称">
              <div class="file-name-row">
                <el-icon><Document /></el-icon>
                <span class="result-filename">{{ uploadResult.originalFileName }}</span>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="文件大小">{{ formatFileSize(uploadResult.fileSize) }}</el-descriptions-item>
            <el-descriptions-item label="下载码">
              <div class="code-box">
                <span>{{ uploadResult.downloadCode }}</span>
                <el-button type="primary" link @click="copyDownloadCode">复制</el-button>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="过期时间">{{ formatTime(uploadResult.expirationTime) }}</el-descriptions-item>
            <el-descriptions-item label="下载链接">
              <div class="link-box">
                <el-input
                  v-model="downloadLink"
                  readonly
                  size="small"
                >
                  <template #append>
                    <el-button @click="copyDownloadLink">复制</el-button>
                  </template>
                </el-input>
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div class="result-actions">
          <el-button
            type="primary"
            @click="resetUpload"
            class="result-action-btn"
          >
            继续上传
          </el-button>
          <el-button @click="$router.push('/')" class="result-action-btn">返回首页</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable vue/valid-v-model */
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { UploadFilled, Upload, DocumentAdd, FolderAdd, Document } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { formatFileSize } from '../utils/format'
import api from '../utils/api'

export default {
  name: 'UploadPage',
  components: {
    UploadFilled,
    Upload,
    DocumentAdd,
    FolderAdd,
    Document
  },
  setup() {
    const activeTab = ref('single')
    
    // 响应式检测
    const isMobile = ref(window.innerWidth <= 768)
    const handleResize = () => {
      isMobile.value = window.innerWidth <= 768
    }
    
    onMounted(() => {
      window.addEventListener('resize', handleResize)
    })
    
    onUnmounted(() => {
      window.removeEventListener('resize', handleResize)
    })
    
    // 单文件上传信息
    const singleFileInfo = reactive({
      file: null,
      expirationDays: 7,
      description: ''
    })
    
    // 多文件上传信息
    const multipleFileInfo = reactive({
      files: [],
      zipName: '',
      expirationDays: 7,
      description: ''
    })
    
    const multipleFileInput = ref(null)
    const folderInput = ref(null)
    
    const uploading = ref(false)
    
    const uploadResult = reactive({
      visible: false,
      originalFileName: '',
      fileSize: 0,
      downloadCode: '',
      downloadUrl: '',
      expirationTime: ''
    })
    
    // 是否可以上传
    const isUploadable = computed(() => {
      if (activeTab.value === 'single') {
        return !!singleFileInfo.file
      } else {
        return multipleFileInfo.files.length > 0
      }
    })
    
    const downloadLink = computed(() => {
      // 构建完整的下载链接，包含当前域名
      if (!uploadResult.downloadUrl) return ''
      const protocol = window.location.protocol
      const host = window.location.host
      return `${protocol}//${host}${uploadResult.downloadUrl}`
    })
    
    // 触发多文件选择
    const triggerMultipleFileInput = () => {
      multipleFileInput.value.click()
    }
    
    // 触发文件夹选择
    const triggerFolderInput = () => {
      folderInput.value.click()
    }
    
    // 处理拖放文件
    const onDropFiles = (event) => {
      const files = event.dataTransfer.files
      addMultipleFiles(files)
    }
    
    // 添加多个文件
    const addMultipleFiles = (files) => {
      // 转换FileList为数组
      const filesArray = Array.from(files)
      
      if (filesArray.length === 0) return
      
      // 添加文件到列表
      multipleFileInfo.files.push(...filesArray)
      
      ElMessage.success(`成功添加 ${filesArray.length} 个文件`)
    }
    
    // 清空多文件列表
    const clearMultipleFiles = () => {
      multipleFileInfo.files = []
    }
    
    // 移除多文件列表中的文件
    const removeMultipleFile = (index) => {
      multipleFileInfo.files.splice(index, 1)
    }
    
    // 单文件变更事件
    const handleSingleFileChange = (file) => {
      // 只取最后一个文件
      singleFileInfo.file = file.raw
    }
    
    // 多文件变更事件
    const handleMultipleFileChange = (event) => {
      addMultipleFiles(event.target.files)
      // 清空input，允许再次选择相同的文件
      event.target.value = ''
    }
    
    // 超出文件数限制
    const handleExceed = () => {
      ElMessage.warning('一次只能上传一个文件')
    }
    
    // 移除单文件
    const handleSingleFileRemove = () => {
      singleFileInfo.file = null
    }
    
    // 格式化时间
    const formatTime = (timeStr) => {
      if (!timeStr) return '暂无信息';
      try {
        // 判断时间格式，可能是ISO格式或普通字符串
        const date = new Date(timeStr);
        if (isNaN(date.getTime())) {
          return timeStr; // 如果无法解析为日期，则原样返回
        }
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        });
      } catch (error) {
        console.error('时间格式化错误', error);
        return timeStr || '暂无信息';
      }
    }
    
    // 上传文件
    const handleUpload = async () => {
      if (!isUploadable.value) {
        ElMessage.warning('请先选择要上传的文件')
        return
      }
      
      uploading.value = true
      
      try {
        let response
        
        if (activeTab.value === 'single') {
          // 单文件上传
          response = await api.uploadFile(
            singleFileInfo.file,
            singleFileInfo.expirationDays,
            singleFileInfo.description
          )
        } else {
          // 多文件上传
          response = await api.uploadMultipleFiles(
            multipleFileInfo.files,
            multipleFileInfo.zipName,
            multipleFileInfo.expirationDays,
            multipleFileInfo.description
          )
        }
        
        const { code, data, message } = response.data
        
        if (code === 200) {
          // 上传成功
          uploadResult.originalFileName = data.originalFileName || '未知文件';
          uploadResult.fileSize = data.fileSize || 0;
          uploadResult.downloadCode = data.downloadCode || '无';
          uploadResult.downloadUrl = data.downloadUrl || '';
          uploadResult.expirationTime = data.expirationTime || '';
          uploadResult.visible = true;
        } else {
          // 上传失败
          ElMessage.error(message || '上传失败')
        }
      } catch (error) {
        console.error('上传错误', error)
        ElMessage.error('文件上传失败，请重试')
      } finally {
        uploading.value = false
      }
    }
    
    // 复制下载码
    const copyDownloadCode = () => {
      navigator.clipboard.writeText(uploadResult.downloadCode)
        .then(() => {
          ElMessage.success('下载码已复制到剪贴板')
        })
        .catch(() => {
          ElMessage.error('复制失败，请手动复制')
        })
    }
    
    // 复制下载链接
    const copyDownloadLink = () => {
      navigator.clipboard.writeText(downloadLink.value)
        .then(() => {
          ElMessage.success('下载链接已复制到剪贴板')
        })
        .catch(() => {
          ElMessage.error('复制失败，请手动复制')
        })
    }
    
    // 重置上传状态
    const resetUpload = () => {
      if (activeTab.value === 'single') {
        singleFileInfo.file = null
      } else {
        multipleFileInfo.files = []
        multipleFileInfo.zipName = ''
      }
      uploadResult.visible = false
    }
    
    return {
      activeTab,
      singleFileInfo,
      multipleFileInfo,
      multipleFileInput,
      folderInput,
      uploading,
      uploadResult,
      downloadLink,
      isUploadable,
      formatFileSize,
      formatTime,
      triggerMultipleFileInput,
      triggerFolderInput,
      onDropFiles,
      addMultipleFiles,
      clearMultipleFiles,
      removeMultipleFile,
      handleSingleFileChange,
      handleMultipleFileChange,
      handleExceed,
      handleSingleFileRemove,
      handleUpload,
      copyDownloadCode,
      copyDownloadLink,
      resetUpload,
      isMobile
    }
  }
}
</script>

<style scoped>
.upload-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  font-size: 1.8rem;
  font-weight: 700;
  color: var(--primary-color);
  margin: 0;
  letter-spacing: -0.5px;
}

.upload-wrapper {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 1.2rem;
  font-weight: 500;
  color: var(--text-color);
}

.custom-tabs :deep(.el-tabs__nav-wrap::after) {
  background-color: var(--border-color);
}

.custom-tabs :deep(.el-tabs__item) {
  color: var(--text-secondary);
  font-weight: 500;
}

.custom-tabs :deep(.el-tabs__item.is-active) {
  color: var(--primary-color);
  font-weight: 600;
}

.custom-tabs :deep(.el-tabs__active-bar) {
  background-color: var(--primary-color);
}

.size-tip {
  font-size: 0.9rem;
  color: var(--text-secondary);
  font-weight: normal;
}

.upload-area {
  width: 100%;
  margin-top: 20px;
}

.el-upload-dragger {
  border-radius: 12px;
  border-color: var(--border-color);
  background-color: var(--background-color);
  transition: all 0.3s;
}

.el-upload-dragger:hover {
  border-color: var(--primary-color);
  background-color: rgba(212, 175, 55, 0.05);
}

.el-icon--upload {
  color: var(--primary-color) !important;
}

.file-info {
  margin-top: 20px;
  padding: 15px;
  background-color: var(--background-color);
  border-radius: 12px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.file-info:hover {
  transform: translateY(-2px);
  box-shadow: var(--card-shadow);
}

.file-info p {
  margin: 8px 0;
  color: var(--text-color);
}

.file-info-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.file-info-header i {
  color: var(--primary-color);
  font-size: 1.5rem;
}

.file-name {
  font-weight: 600;
  font-size: 1.1rem;
  color: var(--text-color);
  word-break: break-all;
}

.multiple-upload-area {
  width: 100%;
  margin-top: 20px;
}

.upload-buttons {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.drop-zone {
  width: 100%;
  height: 200px;
  border: 2px dashed var(--border-color);
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
  background-color: var(--background-color);
}

.drop-zone:hover {
  border-color: var(--primary-color);
  background-color: rgba(212, 175, 55, 0.05);
}

.drop-zone i {
  color: var(--primary-color);
  margin-bottom: 10px;
}

.drop-zone p {
  margin: 10px 0;
  color: var(--text-color);
}

.drop-zone .drop-hint {
  font-size: 12px;
  color: var(--text-secondary);
}

.selected-files {
  margin-top: 20px;
}

.selected-files-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.selected-files-header h4 {
  margin: 0;
  color: var(--text-color);
  font-size: 1.1rem;
  font-weight: 600;
}

.zip-name-input {
  margin-bottom: 15px;
}

.form-options {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid var(--border-color);
}

.form-actions {
  margin-top: 30px;
  text-align: center;
}

.form-actions .el-button {
  min-width: 120px;
  border-radius: 12px;
  padding: 12px 30px;
  font-size: 1.1rem;
  font-weight: 500;
}

.result-box {
  text-align: center;
}

.result-info {
  margin: 20px 0;
}

.custom-descriptions :deep(.el-descriptions__label) {
  background-color: var(--background-color);
  color: var(--text-secondary);
  font-weight: 500;
}

.file-name-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-name-row i {
  color: var(--primary-color);
}

.link-box {
  width: 100%;
}

.result-actions {
  margin-top: 30px;
}

.result-action-btn {
  margin: 0 5px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .upload-container {
    padding: 15px;
  }
  
  .header h2 {
    font-size: 1.5rem;
  }
  
  .upload-buttons {
    flex-wrap: wrap;
  }
  
  .upload-buttons .el-button {
    flex: 1;
    min-width: 140px;
  }
  
  .drop-zone {
    height: 150px;
  }
  
  .form-options .el-form-item {
    margin-bottom: 20px;
  }

  /* 对话框响应式优化 */
  .upload-result-dialog :deep(.el-result__title),
  .upload-result-dialog :deep(.el-result__subtitle) {
    font-size: 14px;
    word-break: break-word;
  }

  .custom-descriptions :deep(.el-descriptions__body) {
    width: 100%;
  }

  .custom-descriptions :deep(.el-descriptions__label) {
    width: 80px;
    min-width: 80px;
    padding: 8px;
  }

  .custom-descriptions :deep(.el-descriptions__content) {
    padding: 8px;
  }

  .result-actions {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
  }

  .result-action-btn {
    margin: 5px 0;
    width: 100%;
  }

  .code-box {
    flex-wrap: wrap;
    gap: 8px;
  }
}

@media (max-width: 480px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .form-actions .el-button {
    width: 100%;
  }
}

/* 上传结果对话框移动端优化 */
.upload-result-dialog :deep(.el-dialog__body) {
  padding: 15px !important;
}

.result-filename {
  word-break: break-all;
  display: inline-block;
}

.code-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.code-box span {
  font-family: monospace;
  font-size: 1.1rem;
  color: var(--primary-color);
  font-weight: 600;
  word-break: break-all;
}
</style> 